﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Data.Entity;
using Legazpi.Payroll.BusinessLogic.Services.Interfaces;
using Legazpi.Payroll.DataAccess.DataObjects;
using Legazpi.Payroll.DataAccess.Base;
using Legazpi.Payroll.DataAccess.Repositories;

namespace Legazpi.Payroll.BusinessLogic.Services
{
    public class RoleService : IRoleService
    {
        #region Fields
        
        private DbContext _dbContext;        
        private IRoleRepository _roleRepository;
        private IUserRepository _userRepository;

        private IDatabaseFactory _dbFactory;
        #endregion
        
        #region ctor

        public RoleService()
            : this(new DatabaseFactory())
        {
            
        }
        
        public RoleService(IDatabaseFactory dbFactory)
        {
           if (dbFactory == null) throw new ArgumentNullException("dbFactory");
            _dbFactory = dbFactory;
            DbContext = dbFactory.Get();     
        }
        
        private DbContext DbContext
        {
            get { return _dbContext; }
            set 
            { 
                _dbContext = value;
                _roleRepository = new RoleRepository(_dbContext);
                _userRepository = new UserRepository(_dbContext);
            }
        }

        #endregion

        #region Implementation of IRoleService    
        
        public Role GetById(int id)
        {
            return _roleRepository.GetById(id);
        }

        public Role GetByRoleName(string rolename)
        {
            return _roleRepository.Get(role => role.RoleName.Equals(rolename));                
        }

        public bool IsUserInRole(string userName, string roleName)
        {
            return _roleRepository.Get(role => role.RoleName == roleName)
                .Users.Where(u => u.UserName == userName).Any();
        }

        public IEnumerable<Role> GetAll()
        {
            return _roleRepository.GetAll();
        }

        public void Add(Role role)
        {
            _roleRepository.Add(role);
        }

        public void Update(Role role)
        {
            _roleRepository.Update(role);
        }

        public void Delete(int id)
        {
            var role = GetById(id);
            if (role != null)
                _roleRepository.Delete(role);
        }
        public bool Save()
        {
            string message;
            _roleRepository.Save(out message) ;
            return message == "Saved";
        }


        #endregion

        #region Private Methods
       
        #endregion





    }
}
